package com.business.action.oa;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.business.bean.oa.ReportDay;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.sf.rose.boot.BootStrap;
import net.sf.rose.file.excel.poi.ExcelUtils;
import net.sf.rose.file.util.FileUtils;
import net.sf.rose.jdbc.KeyGenerator;
import net.sf.rose.jdbc.PageBean;
import net.sf.rose.jdbc.dao.BeanDAO;
import net.sf.rose.jdbc.dao.MapDAO;
import net.sf.rose.jdbc.query.BeanSQL;
import net.sf.rose.jdbc.query.MapSQL;
import net.sf.rose.jdbc.service.Service;
import net.sf.rose.util.DateFormat;
import net.sf.rose.util.StringUtil;
import net.sf.rose.web.util.WebUtils;

/**
 * 考勤日报管理
 * 
 * @author fengjian
 *
 */
@Controller
@RequestMapping("/day/report")
public class DayReportAction {

	/**
	 * 获取所有日报数据
	 */
	@ResponseBody
	@RequestMapping("/page.do")
	public PageBean page(HttpServletRequest request, Service service) {
		PageBean page = WebUtils.getPageBean(request);
		Map<String, Object> map = WebUtils.getRequestData(request);
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.setPage(page);
		query.setEntityClass(ReportDay.class);
		query.setTableName("OA_REPORT_DAY_VIEW");
		query.createSql(map);
		dao.list();
		return page;
	}

	/**
	 * 日报
	 */
	@ResponseBody
	@RequestMapping("/getDayReport.do")
	public PageBean getDayReport(HttpServletRequest request, Service service, String dayReportID) {
		PageBean res = new PageBean();
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.setEntityClass(ReportDay.class);
		query.setTableName("OA_REPORT_DAY_VIEW");
		query.createSql("dayReportID", dayReportID);
		ReportDay bean = dao.get();
		res.setData(bean);
		return res;
	}

	/**
	 * 提交日报
	 */
	@ResponseBody
	@RequestMapping("/submitDayReport.do")
	public PageBean submitDayReport(HttpServletRequest request, Service service, String dayReportIDs) {
		PageBean res = new PageBean();
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.setSQL("update OA_REPORT_DAY set checkStatus=1,submitTime=? where dayReportID=?");
		Date d = new Date();
		String[] arr = StringUtils.split(dayReportIDs, ',');
		for (String str : arr) {
			query.addParameter(d);
			query.addParameter(str);
			dao.update();
			query.clearParameterList();
		}
		return res;
	}

	/**
	 * 审核日报
	 */
	@ResponseBody
	@RequestMapping("/check.do")
	public PageBean checkDayReport(HttpServletRequest request, Service service, ReportDay bean) {
		PageBean res = new PageBean();
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.setSQL("update OA_REPORT_DAY set checkStatus=?,checkUserID=?,checkedTime=? where dayReportID=?");
		Date d = new Date();
		String[] arr = StringUtils.split(bean.getDayReportID(), ',');
		for (String str : arr) {
			//query.addParameter(bean.getCheckStatus());
			query.addParameter(bean.getCheckUserID());
			query.addParameter(d);
			query.addParameter(str);
			dao.update();
			query.clearParameterList();
		}
		return res;
	}

	/**
	 * 日报明细列表
	 */
	@ResponseBody
	@RequestMapping("/getDayReportDetailList.do")
	public PageBean getDayReportDetailList(HttpServletRequest request, Service service) {
		PageBean res = new PageBean();
		Map<String, Object> map = WebUtils.getRequestData(request);
		MapDAO dao = new MapDAO(service);
		MapSQL query = dao.getQuerySQL();
		StringBuilder sb = new StringBuilder();
		sb.append("select projectDayID,userID,calendarDate,projectID,operatorID,workSort,dayReportID,workTime ");
		sb.append("from WORK_PROJECT_DAY where 1=1 ");
		if (map.get("projectID") != null) {
			sb.append("and projectID=? ");
			query.addParameter(map.get("projectID"));
		}
		String from = null, to = null;
		if (map.get("calendarDate_from") != null) {
			from = map.get("calendarDate_from").toString();
		}
		if (map.get("calendarDate_to") != null) {
			to = map.get("calendarDate_to").toString();
		}
		if (from != null || to != null) {
			if (from != null && to != null) {
				sb.append("and calendarDate BETWEEN ? and ? ");
				query.addParameter(from);
				query.addParameter(to);
			} else if (from != null) {
				sb.append("and calendarDate >= ? ");
				query.addParameter(from);
			} else {
				sb.append("and calendarDate <= ? ");
				query.addParameter(to);
			}
		}
		query.addSql("SELECT t1.projectDayID,t1.userID,t1.calendarDate,t1.projectID,t1.workSort,t1.workTime, ");
		query.addSql("t2.projectName,t3.workNo,t3.userName,t4.departName,t5.userName as operatorID,t6.cardRecord ");
		query.addSql("FROM(").addSql(sb.toString()).addSql(") t1 ");
		query.addSql("LEFT JOIN work_project t2 ON t1.projectID = t2.projectID ");
		query.addSql("LEFT JOIN sys_user t3 ON t1.userID = t3.userID ");
		query.addSql("LEFT JOIN departID t4 ON t3.departID = t4.departID ");
		query.addSql("LEFT JOIN sys_user t5 ON t1.operatorID = t5.userID ");
		query.addSql("LEFT JOIN OA_REPORT_DAY t6 ON t1.dayReportID = t6.dayReportID ");
		if (map.get("departID") != null) {
			query.addSql("WHERE t3.departID like ? ");
			query.addParameter(map.get("departID") + "%");
		}
		query.addSql("ORDER BY t1.userID,t1.calendarDate ASC ");
		List<Map<String, Object>> list = dao.list();
		for (Map<String, Object> m : list) {
			Object workSort = m.get("workSort");
			Object workTime = m.remove("workTime");
			if (workSort == null) {
				m.put("workTime", workTime);
			} else {
				int sort = (int) workSort;
				// 正常出勤：1；正常加班：2；周末加班：3；假日加班：4；
				switch (sort) {
				case 1:
					m.put("workTime", workTime);
					break;
				case 2:
					m.put("overTimeDay", workTime);
					break;
				case 3:
					m.put("overTimeWeekend", workTime);
					break;
				case 4:
					m.put("overTimeHoliday", workTime);
					break;
				}
			}
		}
		res.setData(list);
		return res;
	}

	/**
	 * 获取所有日报数据及明细 返回的每一条记录是日报明细，前半部是日报，后半部分是明细内容
	 */
	@ResponseBody
	@RequestMapping("/day/list.do")
	public PageBean listDayReport(HttpServletRequest request, Service service) {
		PageBean page = WebUtils.getPageBean(request);
		// 查日报数据
		Map<String, Object> map = WebUtils.getRequestData(request);
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		// query.setPage(page);
		query.setEntityClass(ReportDay.class);
		query.setTableName("OA_REPORT_DAY_VIEW");
		query.createSql(map);
		query.setPage(page);
		query.addSql(" order by userID,calendarDate desc");
		dao.list();
		return page;
	}

	/**
	 * 保存日报列表数据
	 */
	@ResponseBody
	@RequestMapping("/savetDayReportList.do")
	public PageBean savetDayReportList(Service service, String checkUserID, String json) {
		PageBean res = new PageBean();
		List<ReportDay> list = StringUtil.parseJsonArray(ReportDay.class, json);
		if (list.size() == 0) {
			res.setSuccess(false);
			res.setMessage("没有可保存的数据！");
			return res;
		}
		for (ReportDay bean : list) {
			double d = bean.getWorkTime() + bean.getOverTimeDay() + bean.getOverTimeWeekend()
					+ bean.getOverTimeHoliday();
			bean.setTotalWorkTime(d);
			bean.setCheckStlye("人工考勤");
			bean.setCheckUserID(checkUserID);
		}
		String fields = "workTime,overTimeDay,overTimeWeekend,overTimeHoliday,totalWorkTime,checkStlye,checkUserID";
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.createBatchUpdateSql(fields, list);
		dao.batchUpdate();
		return res;
	}

	/**
	 * 重新计算日报工时
	 */
	@ResponseBody
	@RequestMapping("/computetDayReportList.do")
	public PageBean computetDayReportList(Service service, String ids) {
		PageBean res = new PageBean();
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.setEntityClass(ReportDay.class);
		query.setSQL("select * from OA_REPORT_DAY where dayReportID=?");
		/* WorkDayReportService ws = new WorkDayReportService(service);
		String[] array = StringUtils.split(ids, ',');
		for (String id : array) {
			query.addParameter(id);
			ReportDay report = dao.get();
			if (report != null) {
				ws.countDayReport(report);
			}
			query.clearParameterList();
		} */
		return res;
	}

	/**
	 * 批量重新计算日报工时
	 */
	@ResponseBody
	@RequestMapping("/batchCompute.do")
	public PageBean batchCompute(HttpServletRequest request, Service service) {
		PageBean res = new PageBean();
		Map<String, Object> map = WebUtils.getRequestData(request);
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.setEntityClass(ReportDay.class);
		query.setTableName("OA_REPORT_DAY_SIMPLE_VIEW");
		query.createSql(map);
		List<ReportDay> list = dao.list();
		if (list.size() > 100) {
			Thread t = new Thread() {
				@Override
				public void run() {
					/* Service newService = new Service();
					try {
						WorkDayReportService ws = new WorkDayReportService(newService);
						for (ReportDay report : list) {
							ws.countDayReport(report);
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						newService.close();
					} */
				}
			};
			t.start();
			res.setMessage("要处理的日报记录有" + list.size() + "条，已开启独立线程去处理，请耐心等待...");
		} else {
			/* WorkDayReportService ws = new WorkDayReportService(service);
			for (ReportDay report : list) {
				ws.countDayReport(report);
			} */
			res.setMessage("已处理了" + list.size() + "条日报记录...");
		}
		return res;
	}

	/**
	 * 导出月报列表
	 */
	@ResponseBody
	@RequestMapping("/any/listMonthReportOutput.do")
	public PageBean listMonthReportOutput(HttpServletRequest request, Service service) {
		PageBean page = WebUtils.getPageBean(request);
		Map<String, Object> map = WebUtils.getRequestData(request);
		// 准备数据
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.setEntityClass(ReportDay.class);
		query.setTableName("OA_REPORT_DAY_VIEW");
		query.createSql(map);
		query.addSql(" order by userID,calendarDate desc");
		List<ReportDay> list = dao.list();
		// 一人一个月一条记录
		Map<String, Object> data = new HashMap<>();
		Map<String, ReportDayBean> dataMap = new LinkedHashMap<>();
		for (ReportDay rd : list) {
			ReportDayBean report = dataMap.get(rd.getWorkNo());
			if (report == null) {
				report = new ReportDayBean();
				report.setWorkNo(rd.getWorkNo());
				report.setUserName(rd.getUserName());
				dataMap.put(rd.getWorkNo(), report);
			}
			String s = rd.getCalendarDate();
			s = s.substring(s.lastIndexOf('-') + 1, s.length());
			report.setData(Integer.parseInt(s), rd.getTotalWorkTime());
			data.put(s, rd.getDayType());
		}
		int index = 0;
		List<ReportDayBean> dataList = new ArrayList<>();
		for (ReportDayBean rd : dataMap.values()) {
			index++;
			rd.setIndex(index);
			dataList.add(rd);
		}
		String timeArea = "";
		Object obj = map.get("calendarDate_to");
		if (obj != null) {
			timeArea = obj.toString();
			Date d = DateFormat.format(timeArea, DateFormat.DATE_FORMAT_1);
			timeArea = DateFormat.format(d, "yyyy-MM");
		}
		String departName = "";
		obj = map.get("departName");
		if (obj != null) {
			departName = obj.toString();
		}
		data.put("timeArea", timeArea);
		data.put("departName", departName);
		data.put("list", dataList);
		// 生成文件
		File file = BootStrap.getOSPath();
		file = new File(file, "resource");
		file = new File(file, "生产月报模板.xls");
		ExcelUtils excel = ExcelUtils.getTool(file);
		// 目标文件路径
		String filename = KeyGenerator.getSystemUUID() + ".xls";
		File path = FileUtils.IMAGE_PATH;
		path = new File(path, filename);
		if (excel.write(path, data)) {
			System.out.println(path.getAbsolutePath() + "文件已生成！");
		} else {
			System.out.println(path.getAbsolutePath() + "文件生成失败！");
		}
		page.addDataMap("filename", filename);
		return page;
	}

	/**
	 * 导出日报列表
	 */
	@ResponseBody
	@RequestMapping("/any/listDayReportOutput.do")
	public PageBean listDayReportOutput(HttpServletRequest request, Service service) {
		PageBean page = WebUtils.getPageBean(request);
		Map<String, Object> map = WebUtils.getRequestData(request);
		// 准备数据
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.setEntityClass(ReportDay.class);
		query.setTableName("OA_REPORT_DAY_VIEW");
		query.createSql(map);
		query.addSql(" order by userID,calendarDate desc");
		List<ReportDay> list = dao.list();
		Map<String, Object> data = new HashMap<>();
		String timeArea = "";
		Object obj = map.get("calendarDate_from");
		if (obj != null) {
			timeArea = timeArea + obj;
		}
		timeArea = timeArea + '~';
		obj = map.get("calendarDate_to");
		if (obj != null) {
			timeArea = timeArea + obj;
		}
		data.put("timeArea", timeArea);
		data.put("list", list);
		// 生成文件
		File file = BootStrap.getOSPath();
		file = new File(file, "resource");
		file = new File(file, "生产日报模板.xls");
		ExcelUtils excel = ExcelUtils.getTool(file);
		// 目标文件路径
		String filename = KeyGenerator.getSystemUUID() + ".xls";
		File path = FileUtils.IMAGE_PATH;
		path = new File(path, filename);
		if (excel.write(path, data)) {
			System.out.println(path.getAbsolutePath() + "文件已生成！");
		} else {
			System.out.println(path.getAbsolutePath() + "文件生成失败！");
		}
		page.addDataMap("filename", filename);
		return page;
	}
}
